﻿using AutoMapper;
using MediatR;
using SlaughterItem.Common.Domains.Manages;
using SlaughterItem.Common.Dtos;
using SlaughterItem.Common.Infrastructures.Interfaces;
using SlaughterItem.Enum;

namespace SlaughterItem.API.Application.Commands.Week01.ManageCommands.Busines
{
    public class BusinesCreateHandler : IRequestHandler<BusinesCreateCommand, Result>
    {

        private readonly IBaseRepository<Business> BusinesRepository;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="BusinesRepository"></param>
        /// <param name="mapper"></param>
        public BusinesCreateHandler(IBaseRepository<Business> BusinesRepository, IMapper mapper)
        {
            this.BusinesRepository = BusinesRepository;
            this.mapper = mapper;
        }


        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(BusinesCreateCommand request, CancellationToken cancellationToken)
        {
            var result= new Result() { Code=(int)CommonErrorCode.Added};

            try
            {
                Business business = mapper.Map<Business>(request);
                var list = BusinesRepository.Add(business);

                if (list > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    
                }
                else
                {
                    result.Msg = "失败";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
